aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(app)/ln/[lnurl]/+page.server.ts
blob: 04cff33814ebdc48c5f76f3265461a7e23bd812a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import { PUBLIC_DOMAIN } from "$env/static/public";
import getRates from "$lib/rates";
import { auth, fd, get, post } from "$lib/utils";
import { bech32 } from "@scure/base";
import { error, fail, redirect } from "@sveltejs/kit";
const { decode, fromWords } = bech32;

const lnurlFetch = async (url: string) =>
	get(`/lnurl/proxy?url=${encodeURIComponent(url)}`);

export async function load({ cookies, params, parent }) {
	const { user } = await parent();
	const rates = await getRates();

	let data;
	const { lnurl } = params;

	const url = Buffer.from(fromWords(decode(lnurl, 20000).words)).toString();

	try {
		data = await get(`/decode?text=${lnurl}`);
	} catch (e) {
		const { message } = e as Error;
		error(500, message);
	}

	let { callback, minSendable, maxSendable, comment, tag } = data;
	if (tag === "payRequest" && minSendable === maxSendable) {
		minSendable = Math.round(minSendable / 1000);
		maxSendable = Math.round(maxSendable / 1000);
		const amount = minSendable;

		const urlObj = new URL(callback);
		urlObj.searchParams.set("amount", (amount * 1000).toString());
		if (comment) {
			urlObj.searchParams.set("comment", comment);
		}
		const url = urlObj.toString();

		const { pr } = await lnurlFetch(url);

		let invoice;
		try {
			invoice = await get(`/invoice/${pr}`);
		} catch (e) {}

		if (invoice) redirect(307, `/invoice/${invoice.id}`);

		let path = `/send/lightning/${pr}`;
		if (comment) path += `/${encodeURIComponent(comment)}`;
		redirect(307, path);
	} else if (url.startsWith(`https://${PUBLIC_DOMAIN}/`)) {
		const username = url.split(`https://${PUBLIC_DOMAIN}/p/`)[1];
		if (username) redirect(307, `/pay/${username}`);
	}

	if (!["payRequest", "withdrawRequest"].includes(data.tag))
		error(500, "We only support LNURLp and LNURLw at this time");

	data.rate = rates[user?.currency || "USD"];
	// Lightning sends draw on the main account; the Max button needs its balance
	if (user && data.tag === "payRequest") {
		try {
			({ balance: data.balance } = await get(`/account/${user.id}`, auth(cookies)));
		} catch (e) {}
	}
	return data;
}

export const actions = {
	pay: async ({ fetch, request }) => {
		let error;

		let { callback, amount, minSendable, maxSendable, comment } =
			await fd(request);
		minSendable = Math.round(minSendable / 1000);
		maxSendable = Math.round(maxSendable / 1000);

		if (amount < minSendable)
			error = `Amount must be at least ${minSendable} sats`;
		if (amount > maxSendable)
			error = `Amount must be at most ${maxSendable} sats`;
		if (error) return fail(400, { error });

		const urlObj = new URL(callback);
		urlObj.searchParams.set("amount", (amount * 1000).toString());
		if (comment) urlObj.searchParams.set("comment", comment);
		const url = urlObj.toString();

		const { pr } = await lnurlFetch(url);

		let path = `/send/lightning/${pr}`;
		if (comment) path += `/${encodeURIComponent(comment)}`;
		redirect(307, path);
	},

	// Send everything to an LNURL-pay endpoint. The routing cost depends on the
	// amount and the amount on the routing cost, and the invoice only exists
	// once we name an amount — so fetch a probe invoice at the most we could
	// possibly send (its destination and route hints are what the quote needs),
	// let the server solve for the amount that lands the balance on zero, then
	// fetch the real invoice for exactly that amount.
	max: async ({ cookies, request }) => {
		let { callback, minSendable, maxSendable, comment } = await fd(request);
		minSendable = Math.round(minSendable / 1000);
		maxSendable = Math.round(maxSendable / 1000);

		const user = await get("/me", auth(cookies));
		const { balance } = await get(`/account/${user.id}`, auth(cookies));
		const ceiling = Math.min(balance, maxSendable);
		if (ceiling < minSendable)
			return fail(400, { error: `Amount must be at least ${minSendable} sats` });

		const invoiceFor = async (amount: number) => {
			const urlObj = new URL(callback);
			urlObj.searchParams.set("amount", (amount * 1000).toString());
			if (comment) urlObj.searchParams.set("comment", comment);
			const { pr, reason } = await lnurlFetch(urlObj.toString());
			if (!pr) throw new Error(reason || "Could not fetch invoice");
			return pr;
		};

		let pr;
		try {
			const probe = await invoiceFor(ceiling);
			const { amount } = await post(
				"/lightning/quote",
				{ payreq: probe, max: true, ceiling },
				auth(cookies),
			);
			if (amount < minSendable)
				return fail(400, { error: `Amount must be at least ${minSendable} sats` });
			pr = await invoiceFor(amount);
		} catch (e) {
			const { error } = e as Error & { error?: string };
			return fail(400, { error: (e as Error).message || error });
		}

		let path = `/send/lightning/${pr}`;
		if (comment) path += `/${encodeURIComponent(comment)}`;
		redirect(307, path);
	},

	withdraw: async ({ cookies, fetch, request }) => {
		let error;

		let {
			callback,
			amount,
			username,
			currency,
			minWithdrawable,
			maxWithdrawable,
			k1,
		} = await fd(request);

		minWithdrawable = Math.round(minWithdrawable / 1000);
		maxWithdrawable = Math.round(maxWithdrawable / 1000);

		if (amount < minWithdrawable)
			error = `Amount must be at least ${minWithdrawable} sats`;
		if (amount > maxWithdrawable)
			error = `Amount must be at most ${maxWithdrawable} sats`;
		if (error) return fail(400, { error });

		const invoice = { amount, type: "lightning" };
		const user = { username, currency };

		const { text: pr } = await post(
			"/invoice",
			{ invoice, user },
			auth(cookies),
		);

		const url = new URL(callback);
		url.searchParams.append("k1", k1);
		url.searchParams.append("pr", pr);

		await lnurlFetch(url.toString());

		redirect(307, "/payments");
	},
};